package kaindorfcompany.webshop.productmanagement.frontend.servlets;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kaindorfcompany.webshop.productmanagement.backend.access.DbAccess;
import kaindorfcompany.webshop.productmanagement.backend.data.Ingredient;
import kaindorfcompany.webshop.productmanagement.backend.data.Product;
import kaindorfcompany.webshop.productmanagement.frontend.servlets.util.ServletUtil;

@WebServlet("/admin/products/edit")
public class ProductEditServlet extends HttpServlet {

    /**
     * Serve the system manager a view for adding a product
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String idStr = request.getParameter("productId");
        if (idStr == null) {
            ServletUtil.showGeneralError("Must provide productId", request, response);
            return;
        }
        int productId;
        try {
            productId = Integer.parseInt(idStr);
        } catch (NumberFormatException ex) {
            ServletUtil.showGeneralError("Illegal product id", request, response);
            return;
        }
        LinkedList<Product> products = DbAccess.getInstance().getProducts();
        Product product = null;
        for (Product product1 : products) {
            if (product1.getId() == productId) {
                product = product1;
                break;
            }
        }

        request.setAttribute("product", product);

        List<Ingredient> ingredients = DbAccess.getInstance().getIngredients(true);
        request.setAttribute("ingredients", ingredients);
        ServletUtil.forwardToView(request, response, "editProduct");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int productId = Integer.parseInt(request.getParameter("productId"));
        String designation = request.getParameter("designation");
        String url = request.getParameter("url");
        double price = Double.parseDouble(request.getParameter("price"));

        String[] ingredientsParam = request.getParameterValues("ingredients");

        if (designation == null || designation.isEmpty()) {
            ServletUtil
                    .showGeneralError("The designation of the product must not be null or empty!", request, response);
            return;
        }

        if (url == null) {
            ServletUtil.showGeneralError("The url of the product must not be null", request, response);
            return;
        }

        if (price <= 0) {
            ServletUtil.showGeneralError("The price must not be negative", request, response);
            return;
        }
        DbAccess.getInstance().removeProduct(productId);

        int[] ingredientIds = null;
        Product product = new Product(productId, designation, url, price);
        DbAccess dbAccess = DbAccess.getInstance();
        if (ingredientsParam != null) {
            ingredientIds = new int[ingredientsParam.length];
            int i = 0;
            for (String string : ingredientsParam) {
                ingredientIds[i++] = Integer.parseInt(string);
            }
        }
        dbAccess.addProduct(product);
        if (ingredientsParam != null) {
            for (int ingredientId : ingredientIds) {
                DbAccess.getInstance().addIngredientToProduct(product.getId(), ingredientId);
            }
        }

        ServletUtil.redirect(response, "/webshop/admin/products");
    }
}
